package com.cvai.controller;


import com.alibaba.fastjson.JSON;
import com.cvai.R.PageResult;
import com.cvai.R.Result;
import com.cvai.domain.dto.LoginDto;
import com.cvai.domain.vo.UserVo;
import com.cvai.service.IUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cv
 * @since 2025-03-09
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
@Slf4j
@RequiredArgsConstructor
public class UserController {
    private final IUserService userService;

    @PostMapping("/login")
    public Result<UserVo> login(@RequestBody LoginDto loginDto) {
        return Result.success(userService.login(loginDto));
    }

    @PostMapping("/register")
    public Result<UserVo> register(@RequestBody LoginDto loginDto) {
        return Result.success(userService.register(loginDto));
    }

    @GetMapping("/chat/list")
    public Result<PageResult> list(@RequestParam(required = false) Integer pageNum) {
        PageResult result=userService.getChatList(pageNum);
        return Result.success(result);
    }

    @GetMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback")
    public void login(AuthCallback callback,HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        AuthResponse login = authRequest.login(callback);
        String code = userService.render(login);
        log.info("code:{}",code);
        response.sendRedirect("http://localhost:5173/oauth-callback?code="+code);
    }

    @GetMapping("/code/{code}")
    public Result<UserVo> getUser(@PathVariable String code) {
        return Result.success(userService.getUserVo(code));
    }
    private AuthRequest getAuthRequest() {
        return new AuthGiteeRequest(AuthConfig.builder()
                .clientId("7b54c3664b6298605eb79065a9c3f1dc400505810358765dc8b1f4dbc9e2fffc")
                .clientSecret("975b28d3c3b7a9cb88852f030587de308a768c956949b69f66088738f0046920")
                .redirectUri("http://localhost:8080/user/callback")
                .ignoreCheckState(true)
                .build());
    }

    @GetMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        userService.logout(request);
        return Result.success("退出成功");
    }
}
